package com.ja.openchat.viewmodels;

import android.app.Application;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.ui.MainActivity;
import com.ja.openchat.ui.login.SetNickNameFragment;
import com.xinstall.XInstall;
import com.xinstall.listener.XInstallAdapter;
import com.xinstall.model.XAppData;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.AuthUserManager;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.config.AppConfigInfo;
import com.zy.openchat.core.model.user.UserInfo;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;

import static com.blankj.utilcode.util.StringUtils.getString;


public class PhoneCodeViewModel extends BaseViewModel {

    public String channelStr = "";
    public String inviteStr = "";
    public String userName = "";
    public String password = "";

    //手机号的绑定
    public ObservableField<String> phone = new ObservableField<>("");
    private String curCountryCode;
    private String curPhone;
    public static final String TOKEN_PHONECODEVIEWMODEL_FINISH = "token_phonecodeviewmodel_finish";

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    AppConfigInfo appConfigInfo;


    public class UIChangeObservable {
        //倒计时观察者
        public SingleLiveEvent<String> timerEvent = new SingleLiveEvent<>();
    }

    public PhoneCodeViewModel(@NonNull Application application) {
        super(application);
        appConfigInfo = AppConfigInfo.getAppWithoutLoginConfigInfo();
        Messenger.getDefault().register(this, TOKEN_PHONECODEVIEWMODEL_FINISH, () -> finish());
    }

    //提交按钮的点击事件
    public BindingCommand confirmOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            sendCode();
        }
    });

    public void setData(Bundle bundle) {
        if (bundle != null) {
            curCountryCode = bundle.getString("code");
            curPhone = bundle.getString("phone");
            userName = bundle.getString("userName");
            password = bundle.getString("password");
            inviteStr = bundle.getString("inviteStr");
            channelStr = bundle.getString("channelStr");
            phone.set(curCountryCode + " " + curPhone);
        }
    }


    public void check(String smsCode) {
        showProgress();
        TelegramManager.getTelegramManager().checkAuthenticationCode(getApplication(), smsCode, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    if (obj.errCode == 420) {//验证码错误次数过多，请5分钟后重新登录
                        showErrorTip(getString(R.string.invalid_sms_code_is_block));
                        finish();
                    } else {
                        showErrorTip(getString(R.string.invalid_sms_code));
                    }
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(final TgEvent tg_event) {
        switch (tg_event.event) {
            case EUser_Td_Register:
                Bundle bundle = new Bundle();
                bundle.putString("curCountryCode", curCountryCode);
                bundle.putString("curPhone", curPhone);
                startContainerActivity(SetNickNameFragment.class.getCanonicalName(), bundle);
                finish();
                break;
            case EUser_Td_Ready:
                //清理数据
                AuthUserManager.cleanDestroyFolder();
                //登录
                AuthUserManager.getAuthUserManager().login(String.format("%s%s", curCountryCode, curPhone), UserInfo.getUserInfo().data_directory);
                //跳转主页面
                startActivity(MainActivity.class);
                Messenger.getDefault().sendNoMsg(RegisterViewModel.TOKEN_REGISTERVIEWMODEL_FINISH);
                Messenger.getDefault().sendNoMsg(LoginViewModel.TOKEN_LOGINVIEWMODEL_FINISH);
                Messenger.getDefault().sendNoMsg(LoginByPhoneViewModel.TOKEN_LOGINBYPHONEVIEWMODEL_FINISH);
                finish();
                break;
            default:
                break;
        }
    }

    private void sendCode() {
        UserInfo.getUserInfo().isPasswordLoginType = true;
        UserInfo.getUserInfo().isPasswordRegisterType = true;
        UserInfo.getUserInfo().phone_number = null;
        showProgress();
        String phone = "";
        if (appConfigInfo != null) {
            phone = appConfigInfo.register_need_phone_code ? String.format("%s%s", curCountryCode + "", curPhone).replace("+", "") : "";
        }
        String inviteStrLim = appConfigInfo.register_need_inviter ? inviteStr : inviteStr;
        TelegramManager.getTelegramManager().setAuthenticationPhoneNumber(getApplication()
                , true, phone
                , userName
                , password
                , channelStr
                , inviteStrLim, new TgResultBlock<TgResponse>() {
                    @Override
                    public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                        hideProgress();
                        if (!obj.ok) {
                            if (obj.errCode == 400) {
                                if ("400_USERNAME_NOT_EXIST".equals(obj.errString) || "400_USERNAME_INVALID".equals(obj.errString)) {
                                    showErrorTip(getApplication().getString(R.string.invalid_username));
                                    return;
                                }
                                if ("400_PASSWORD_VERIFY_INVALID".equals(obj.errString)) {
                                    showErrorTip(getApplication().getString(R.string.invalid_password));
                                    return;
                                }
                                if ("400_IP_ADDRESS_BANNED".equals(obj.errString)) {
                                    showErrorTip(getApplication().getString(R.string.login_ip_disabled));
                                    return;
                                }
                                if ("400_USER_BINDED_IP_ADDRESS".equals(obj.errString)) {
                                    showErrorTip(getApplication().getString(R.string.user_ip_bound));
                                    return;
                                }
                                if ("400_INVITE_CODE_INVALID".equals(obj.errString)) {
                                    showErrorTip(getApplication().getString(R.string.invitation_code_invalid));
                                    return;
                                }
                                if ("400_PHONE_NUMBER_OCCUPIED".equals(obj.errString)) {
                                    showErrorTip(getApplication().getString(R.string.mobile_is_registered));
                                    return;
                                }
                                if ("400_PHONE_NUMBER_INVALID".equals(obj.errString)) {
                                    showErrorTip(getApplication().getString(R.string.invalid_phone_number));
                                    return;
                                }
                                if ("400_USER_PASSWORD_NEEDED".equals(obj.errString)) {
                                    showErrorTip(getApplication().getString(R.string.pwd_required));
                                    return;
                                }
                                if ("400_INVITE_CODE_INVALID".equals(obj.errString)) {
                                    showErrorTip(getApplication().getString(R.string.invitation_code_invalid));
                                    return;
                                }
                                if ("400_USER_PASSWORD_NOT_SET".equals(obj.errString)) {
                                    showErrorTip(getApplication().getString(R.string.pwd_not_set));
                                    return;
                                }
                                if ("400_USERNAME_OCCUPIED".equals(obj.errString)) {
                                    showErrorTip(getApplication().getString(R.string.username_already_taken));
                                    return;
                                }
                                if("400_PHONE_NUMBER_APP_SIGNUP_FORBIDDEN".equals(obj.errString)){
                                    showErrorTip(getApplication().getString(R.string.ip_registration_restrictions));
                                    return;
                                }

                            }
                            showErrorTip(getApplication().getString(R.string.registration_failed));
                        }else {
                            startCountDown();
                        }
                    }

                    @Override
                    public void onTimeout(Map<String, Object> request) {
                        hideProgress();
                        showErrorTip(getString(R.string.request_error));
                    }
                });
    }

    public void startCountDown(){
        addSubscribe(Flowable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(aLong -> {
                    int time = (int) (59 - aLong);
                    KLog.d("aLong==" + time);
                    if (time > 0) {
                        uc.timerEvent.setValue(App.getInstanse().getString(R.string.resend_verify_code)+"（"+time+"）");
                    } else {
                        uc.timerEvent.setValue(App.getInstanse().getString(R.string.resend_verify_code));
                    }
                })
                .doOnComplete(() -> {
                    //倒计时完毕事件处理
                    KLog.d("doOnComplete==");
                    uc.timerEvent.setValue(App.getInstanse().getString(R.string.resend_verify_code));
                })
                .subscribe());
    }
}
